package cn.cscb.mms.server.interceptor;

import cn.cscb.mms.common.context.BaseContext;
import cn.cscb.mms.common.result.Result;
import cn.cscb.mms.common.result.ResultEnum;
import cn.cscb.mms.common.utils.JwtUtil;
import cn.hutool.core.lang.Assert;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            // 拦截的不是动态方法则直接放行
            return true;
        }

        // 从请求头中获取jwt token

        try {
            String jwt = request.getHeader("Authorization");
            Assert.notBlank(jwt);
            log.info("jwt = {}", jwt);
            Map map = jwtUtil.checkJwt(jwt);
            String empNo = map.get("empNo").toString();
            log.info("从jwt中解析出的员工号：{}",empNo);
            BaseContext.setCurrentEmpNo(empNo);
            return true;
        } catch (Exception ex) {
            log.error("Authorization failed", ex);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            String data = objectMapper.writeValueAsString(Result.error(ResultEnum.FORBIDDEN.getCode(), ResultEnum.FORBIDDEN.getMessage()));
            response.getWriter().write(data);
            return false;
        }
    }
}
